package com.jetpackframework.room;

import android.content.Context;


import androidx.annotation.Nullable;
import androidx.sqlite.db.SupportSQLiteDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;

import net.sqlcipher.DatabaseErrorHandler;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteDatabaseHook;
import net.sqlcipher.database.SQLiteOpenHelper;


public class OpenHelper extends SQLiteOpenHelper {

    private final SupportSQLiteOpenHelper.Callback callback;
    private SqliteDatabase[] database;

    public OpenHelper(@Nullable Context context, @Nullable String name, final SupportSQLiteOpenHelper.Callback callback, final SqliteDatabase[] database) {

        super(context, name, null, callback.version, new SQLiteDatabaseHook() {
            @Override
            public void preKey(SQLiteDatabase database) {

            }

            @Override
            public void postKey(SQLiteDatabase database) {

            }
        }, new DatabaseErrorHandler() {
            @Override
            public void onCorruption(SQLiteDatabase dbObj) {
                if (database[0] == null){
                    database[0] = new SqliteDatabase(dbObj);
                }
                callback.onCorruption(database[0]);
            }
        });
        this.callback = callback;
        this.database = database;
    }

    public SupportSQLiteDatabase getDB(byte[] passphrase) {
        SQLiteDatabase database = super.getWritableDatabase(passphrase);
        return getWrapDatabase(database);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        callback.onCreate(getWrapDatabase(db));
    }

    public SupportSQLiteDatabase getWrapDatabase(SQLiteDatabase db) {
        if (database[0] == null){
            database[0] = new SqliteDatabase(db);
        }
        return database[0];
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        callback.onUpgrade(getWrapDatabase(db),oldVersion,newVersion);
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        callback.onOpen(db);
    }
}
